home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / copy.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  14.3 KB  |  508 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. '''Generic (shallow and deep) copying operations.
  5.  
  6. Interface summary:
  7.  
  8.         import copy
  9.  
  10.         x = copy.copy(y)        # make a shallow copy of y
  11.         x = copy.deepcopy(y)    # make a deep copy of y
  12.  
  13. For module specific errors, copy.Error is raised.
  14.  
  15. The difference between shallow and deep copying is only relevant for
  16. compound objects (objects that contain other objects, like lists or
  17. class instances).
  18.  
  19. - A shallow copy constructs a new compound object and then (to the
  20.   extent possible) inserts *the same objects* into in that the
  21.   original contains.
  22.  
  23. - A deep copy constructs a new compound object and then, recursively,
  24.   inserts *copies* into it of the objects found in the original.
  25.  
  26. Two problems often exist with deep copy operations that don\'t exist
  27. with shallow copy operations:
  28.  
  29.  a) recursive objects (compound objects that, directly or indirectly,
  30.     contain a reference to themselves) may cause a recursive loop
  31.  
  32.  b) because deep copy copies *everything* it may copy too much, e.g.
  33.     administrative data structures that should be shared even between
  34.     copies
  35.  
  36. Python\'s deep copy operation avoids these problems by:
  37.  
  38.  a) keeping a table of objects already copied during the current
  39.     copying pass
  40.  
  41.  b) letting user-defined classes override the copying operation or the
  42.     set of components copied
  43.  
  44. This version does not copy types like module, class, function, method,
  45. nor stack trace, stack frame, nor file, socket, window, nor array, nor
  46. any similar types.
  47.  
  48. Classes can use the same interfaces to control copying that they use
  49. to control pickling: they can define methods called __getinitargs__(),
  50. __getstate__() and __setstate__().  See the documentation for module
  51. "pickle" for information on these methods.
  52. '''
  53. import types
  54. from copy_reg import dispatch_table
  55.  
  56. class Error(Exception):
  57.     pass
  58.  
  59. error = Error
  60.  
  61. try:
  62.     from org.python.core import PyStringMap
  63. except ImportError:
  64.     PyStringMap = None
  65.  
  66. __all__ = [
  67.     'Error',
  68.     'copy',
  69.     'deepcopy']
  70.  
  71. def copy(x):
  72.     """Shallow copy operation on arbitrary Python objects.
  73.  
  74.     See the module's __doc__ string for more info.
  75.     """
  76.     cls = type(x)
  77.     copier = _copy_dispatch.get(cls)
  78.     if copier:
  79.         return copier(x)
  80.     
  81.     copier = getattr(cls, '__copy__', None)
  82.     if copier:
  83.         return copier(x)
  84.     
  85.     reductor = dispatch_table.get(cls)
  86.     if reductor:
  87.         rv = reductor(x)
  88.     else:
  89.         reductor = getattr(x, '__reduce_ex__', None)
  90.         if reductor:
  91.             rv = reductor(2)
  92.         else:
  93.             reductor = getattr(x, '__reduce__', None)
  94.             if reductor:
  95.                 rv = reductor()
  96.             else:
  97.                 raise Error('un(shallow)copyable object of type %s' % cls)
  98.     return _reconstruct(x, rv, 0)
  99.  
  100. _copy_dispatch = d = { }
  101.  
  102. def _copy_atomic(x):
  103.     return x
  104.  
  105. d[types.NoneType] = _copy_atomic
  106. d[types.IntType] = _copy_atomic
  107. d[types.LongType] = _copy_atomic
  108. d[types.FloatType] = _copy_atomic
  109. d[types.BooleanType] = _copy_atomic
  110.  
  111. try:
  112.     d[types.ComplexType] = _copy_atomic
  113. except AttributeError:
  114.     pass
  115.  
  116. d[types.StringType] = _copy_atomic
  117.  
  118. try:
  119.     d[types.UnicodeType] = _copy_atomic
  120. except AttributeError:
  121.     pass
  122.  
  123.  
  124. try:
  125.     d[types.CodeType] = _copy_atomic
  126. except AttributeError:
  127.     pass
  128.  
  129. d[types.TypeType] = _copy_atomic
  130. d[types.XRangeType] = _copy_atomic
  131. d[types.ClassType] = _copy_atomic
  132. d[types.BuiltinFunctionType] = _copy_atomic
  133.  
  134. def _copy_list(x):
  135.     return x[:]
  136.  
  137. d[types.ListType] = _copy_list
  138.  
  139. def _copy_tuple(x):
  140.     return x[:]
  141.  
  142. d[types.TupleType] = _copy_tuple
  143.  
  144. def _copy_dict(x):
  145.     return x.copy()
  146.  
  147. d[types.DictionaryType] = _copy_dict
  148. if PyStringMap is not None:
  149.     d[PyStringMap] = _copy_dict
  150.  
  151.  
  152. def _copy_inst(x):
  153.     if hasattr(x, '__copy__'):
  154.         return x.__copy__()
  155.     
  156.     if hasattr(x, '__getinitargs__'):
  157.         args = x.__getinitargs__()
  158.         y = x.__class__(*args)
  159.     else:
  160.         y = _EmptyClass()
  161.         y.__class__ = x.__class__
  162.     if hasattr(x, '__getstate__'):
  163.         state = x.__getstate__()
  164.     else:
  165.         state = x.__dict__
  166.     if hasattr(y, '__setstate__'):
  167.         y.__setstate__(state)
  168.     else:
  169.         y.__dict__.update(state)
  170.     return y
  171.  
  172. d[types.InstanceType] = _copy_inst
  173. del d
  174.  
  175. def deepcopy(x, memo = None, _nil = []):
  176.     """Deep copy operation on arbitrary Python objects.
  177.  
  178.     See the module's __doc__ string for more info.
  179.     """
  180.     if memo is None:
  181.         memo = { }
  182.     
  183.     d = id(x)
  184.     y = memo.get(d, _nil)
  185.     if y is not _nil:
  186.         return y
  187.     
  188.     cls = type(x)
  189.     copier = _deepcopy_dispatch.get(cls)
  190.     if copier:
  191.         y = copier(x, memo)
  192.     else:
  193.         
  194.         try:
  195.             issc = issubclass(cls, type)
  196.         except TypeError:
  197.             issc = 0
  198.  
  199.         if issc:
  200.             y = _deepcopy_atomic(x, memo)
  201.         else:
  202.             copier = getattr(x, '__deepcopy__', None)
  203.             if copier:
  204.                 y = copier(memo)
  205.             else:
  206.                 reductor = dispatch_table.get(cls)
  207.                 if reductor:
  208.                     rv = reductor(x)
  209.                 else:
  210.                     reductor = getattr(x, '__reduce_ex__', None)
  211.                     if reductor:
  212.                         rv = reductor(2)
  213.                     else:
  214.                         reductor = getattr(x, '__reduce__', None)
  215.                         if reductor:
  216.                             rv = reductor()
  217.                         else:
  218.                             raise Error('un(deep)copyable object of type %s' % cls)
  219.                 y = _reconstruct(x, rv, 1, memo)
  220.     memo[d] = y
  221.     _keep_alive(x, memo)
  222.     return y
  223.  
  224. _deepcopy_dispatch = d = { }
  225.  
  226. def _deepcopy_atomic(x, memo):
  227.     return x
  228.  
  229. d[types.NoneType] = _deepcopy_atomic
  230. d[types.IntType] = _deepcopy_atomic
  231. d[types.LongType] = _deepcopy_atomic
  232. d[types.FloatType] = _deepcopy_atomic
  233. d[types.BooleanType] = _deepcopy_atomic
  234.  
  235. try:
  236.     d[types.ComplexType] = _deepcopy_atomic
  237. except AttributeError:
  238.     pass
  239.  
  240. d[types.StringType] = _deepcopy_atomic
  241.  
  242. try:
  243.     d[types.UnicodeType] = _deepcopy_atomic
  244. except AttributeError:
  245.     pass
  246.  
  247.  
  248. try:
  249.     d[types.CodeType] = _deepcopy_atomic
  250. except AttributeError:
  251.     pass
  252.  
  253. d[types.TypeType] = _deepcopy_atomic
  254. d[types.XRangeType] = _deepcopy_atomic
  255. d[types.ClassType] = _deepcopy_atomic
  256. d[types.BuiltinFunctionType] = _deepcopy_atomic
  257.  
  258. def _deepcopy_list(x, memo):
  259.     y = []
  260.     memo[id(x)] = y
  261.     for a in x:
  262.         y.append(deepcopy(a, memo))
  263.     
  264.     return y
  265.  
  266. d[types.ListType] = _deepcopy_list
  267.  
  268. def _deepcopy_tuple(x, memo):
  269.     y = []
  270.     for a in x:
  271.         y.append(deepcopy(a, memo))
  272.     
  273.     d = id(x)
  274.     
  275.     try:
  276.         return memo[d]
  277.     except KeyError:
  278.         pass
  279.  
  280.     for i in range(len(x)):
  281.         if x[i] is not y[i]:
  282.             y = tuple(y)
  283.             break
  284.             continue
  285.     else:
  286.         y = x
  287.     memo[d] = y
  288.     return y
  289.  
  290. d[types.TupleType] = _deepcopy_tuple
  291.  
  292. def _deepcopy_dict(x, memo):
  293.     y = { }
  294.     memo[id(x)] = y
  295.     for key, value in x.iteritems():
  296.         y[deepcopy(key, memo)] = deepcopy(value, memo)
  297.     
  298.     return y
  299.  
  300. d[types.DictionaryType] = _deepcopy_dict
  301. if PyStringMap is not None:
  302.     d[PyStringMap] = _deepcopy_dict
  303.  
  304.  
  305. def _keep_alive(x, memo):
  306.     '''Keeps a reference to the object x in the memo.
  307.  
  308.     Because we remember objects by their id, we have
  309.     to assure that possibly temporary objects are kept
  310.     alive by referencing them.
  311.     We store a reference at the id of the memo, which should
  312.     normally not be used unless someone tries to deepcopy
  313.     the memo itself...
  314.     '''
  315.     
  316.     try:
  317.         memo[id(memo)].append(x)
  318.     except KeyError:
  319.         memo[id(memo)] = [
  320.             x]
  321.  
  322.  
  323.  
  324. def _deepcopy_inst(x, memo):
  325.     if hasattr(x, '__deepcopy__'):
  326.         return x.__deepcopy__(memo)
  327.     
  328.     if hasattr(x, '__getinitargs__'):
  329.         args = x.__getinitargs__()
  330.         args = deepcopy(args, memo)
  331.         y = x.__class__(*args)
  332.     else:
  333.         y = _EmptyClass()
  334.         y.__class__ = x.__class__
  335.     memo[id(x)] = y
  336.     if hasattr(x, '__getstate__'):
  337.         state = x.__getstate__()
  338.     else:
  339.         state = x.__dict__
  340.     state = deepcopy(state, memo)
  341.     if hasattr(y, '__setstate__'):
  342.         y.__setstate__(state)
  343.     else:
  344.         y.__dict__.update(state)
  345.     return y
  346.  
  347. d[types.InstanceType] = _deepcopy_inst
  348.  
  349. def _reconstruct(x, info, deep, memo = None):
  350.     if isinstance(info, str):
  351.         return x
  352.     
  353.     if not isinstance(info, tuple):
  354.         raise AssertionError
  355.     if memo is None:
  356.         memo = { }
  357.     
  358.     n = len(info)
  359.     if not n in (2, 3, 4, 5):
  360.         raise AssertionError
  361.     (callable, args) = info[:2]
  362.     if n > 2:
  363.         state = info[2]
  364.     else:
  365.         state = { }
  366.     if n > 3:
  367.         listiter = info[3]
  368.     else:
  369.         listiter = None
  370.     if n > 4:
  371.         dictiter = info[4]
  372.     else:
  373.         dictiter = None
  374.     if deep:
  375.         args = deepcopy(args, memo)
  376.     
  377.     y = callable(*args)
  378.     memo[id(x)] = y
  379.     if listiter is not None:
  380.         for item in listiter:
  381.             if deep:
  382.                 item = deepcopy(item, memo)
  383.             
  384.             y.append(item)
  385.         
  386.     
  387.     if dictiter is not None:
  388.         for key, value in dictiter:
  389.             if deep:
  390.                 key = deepcopy(key, memo)
  391.                 value = deepcopy(value, memo)
  392.             
  393.             y[key] = value
  394.         
  395.     
  396.     if state:
  397.         if deep:
  398.             state = deepcopy(state, memo)
  399.         
  400.         if hasattr(y, '__setstate__'):
  401.             y.__setstate__(state)
  402.         elif isinstance(state, tuple) and len(state) == 2:
  403.             (state, slotstate) = state
  404.         else:
  405.             slotstate = None
  406.         if state is not None:
  407.             y.__dict__.update(state)
  408.         
  409.         if slotstate is not None:
  410.             for key, value in slotstate.iteritems():
  411.                 setattr(y, key, value)
  412.             
  413.         
  414.     
  415.     return y
  416.  
  417. del d
  418. del types
  419.  
  420. class _EmptyClass:
  421.     pass
  422.  
  423.  
  424. def _test():
  425.     l = [
  426.         None,
  427.         1,
  428.         0x2L,
  429.         3.1400000000000001,
  430.         'xyzzy',
  431.         (1, 0x2L),
  432.         [
  433.             3.1400000000000001,
  434.             'abc'],
  435.         {
  436.             'abc': 'ABC' },
  437.         (),
  438.         [],
  439.         { }]
  440.     l1 = copy(l)
  441.     print l1 == l
  442.     l1 = map(copy, l)
  443.     print l1 == l
  444.     l1 = deepcopy(l)
  445.     print l1 == l
  446.     
  447.     class C:
  448.         
  449.         def __init__(self, arg = None):
  450.             self.a = 1
  451.             self.arg = arg
  452.             if __name__ == '__main__':
  453.                 import sys
  454.                 file = sys.argv[0]
  455.             else:
  456.                 file = __file__
  457.             self.fp = open(file)
  458.             self.fp.close()
  459.  
  460.         
  461.         def __getstate__(self):
  462.             return {
  463.                 'a': self.a,
  464.                 'arg': self.arg }
  465.  
  466.         
  467.         def __setstate__(self, state):
  468.             for key, value in state.iteritems():
  469.                 setattr(self, key, value)
  470.             
  471.  
  472.         
  473.         def __deepcopy__(self, memo = None):
  474.             new = self.__class__(deepcopy(self.arg, memo))
  475.             new.a = self.a
  476.             return new
  477.  
  478.  
  479.     c = C('argument sketch')
  480.     l.append(c)
  481.     l2 = copy(l)
  482.     print l == l2
  483.     print l
  484.     print l2
  485.     l2 = deepcopy(l)
  486.     print l == l2
  487.     print l
  488.     print l2
  489.     l.append({
  490.         l[1]: l,
  491.         'xyz': l[2] })
  492.     l3 = copy(l)
  493.     import repr
  494.     print map(repr.repr, l)
  495.     print map(repr.repr, l1)
  496.     print map(repr.repr, l2)
  497.     print map(repr.repr, l3)
  498.     l3 = deepcopy(l)
  499.     import repr
  500.     print map(repr.repr, l)
  501.     print map(repr.repr, l1)
  502.     print map(repr.repr, l2)
  503.     print map(repr.repr, l3)
  504.  
  505. if __name__ == '__main__':
  506.     _test()
  507.  
  508.